//
//  NYFollowViewController.m
//  百思不得姐
//
//  Created by Apple on 15/9/1.
//  Copyright (c) 2015年 Neal. All rights reserved.
//

#import "NYFollowViewController.h"
#import "NYFollowCategoryCell.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import "NYFollowCategory.h"
#import <MJRefresh.h>
#import "NYFollowTagCell.h"
#import "NYFollowUser.h"
#import <SVProgressHUD.h>
#define NYSelectedCategory ((NYFollowCategory *)self.categoryarray[self.categoryTable.indexPathForSelectedRow.row])

static NSString *const categorycell = @"categorycell";
static NSString *const usercell = @"usercell";

@interface NYFollowViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *categoryTable;
@property (weak, nonatomic) IBOutlet UITableView *userTable;
/* afn */
@property(nonatomic , weak) AFHTTPSessionManager *manager;
/* category */
@property(nonatomic , strong) NSMutableArray *categoryarray;
/* <#注释#> */
@property(nonatomic , strong) NSMutableArray *users;

@end

@implementation NYFollowViewController
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (NSMutableArray *)categoryarray
{
    if (_categoryarray == nil) {
        _categoryarray = [NSMutableArray array];
    }
    return _categoryarray;
}
- (NSMutableArray *)users
{
    if (_users == nil) {
        _users = [NSMutableArray array];
    }
    return _users;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTable];
    [self loadCategories];
    [self setuprefresh];
}
- (void)setuprefresh
{
    self.userTable.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    
    self.userTable.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
}
- (void)loadNewUsers
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NYFollowCategory *selectedcategory = self.categoryarray[self.categoryTable.indexPathForSelectedRow.row];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"]= selectedcategory.ID;
    
    NYWeakSelf;
    [self.manager GET:NYBaseURL parameters:params success:^(NSURLSessionDataTask * task, id responseObject) {
        selectedcategory.users = [NYFollowUser objectArrayWithKeyValuesArray:responseObject[@"list"]];
        selectedcategory.page = 1;
        [weakSelf.userTable reloadData];
        if (selectedcategory.users.count >= [responseObject[@"total"] intValue]) {
            weakSelf.userTable.footer.hidden = YES;
        }
        [weakSelf.userTable.header endRefreshing];
    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        [weakSelf.userTable.header endRefreshing];

    }];
}
- (void)loadMoreUsers
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];

    NYFollowCategory *selectedcategory = self.categoryarray[self.categoryTable.indexPathForSelectedRow.row];
    NSInteger page = selectedcategory.page + 1;
    NSLog(@"%zd",selectedcategory.page);

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"]= selectedcategory.ID;
    params[@"page"] = @(page);
    NYWeakSelf;
    [self.manager GET:NYBaseURL parameters:params success:^(NSURLSessionDataTask * task, id responseObject) {
        
        NSArray *newlist = [NYFollowUser objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [selectedcategory.users addObjectsFromArray:newlist];
        selectedcategory.page = page;
        [weakSelf.userTable reloadData];
        if (selectedcategory.users.count>=[responseObject[@"total"] intValue]) {
            weakSelf.userTable.footer.hidden = YES;
        } else {
            [weakSelf.userTable.footer endRefreshing];
        }

    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        [weakSelf.userTable.footer endRefreshing];
    }];

}
- (void)loadCategories
{    [SVProgressHUD showInfoWithStatus:@"正在加载,," maskType:SVProgressHUDMaskTypeBlack];

    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    parma[@"a"] = @"category";
    parma[@"c"] = @"subscribe";
    
    NYWeakSelf;
    [self.manager GET:NYBaseURL parameters:parma success:^(NSURLSessionDataTask * task, id responseObject) {
        weakSelf.categoryarray = [NYFollowCategory objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [self.categoryTable reloadData];
        
        [weakSelf.categoryTable selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];

        [weakSelf.userTable.header beginRefreshing];
        [SVProgressHUD dismiss];

    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        [SVProgressHUD showErrorWithStatus:@"网络不给力"];
    }];
}
- (void)setupTable
{
    self.categoryTable.backgroundColor = NYGlobalBg;
    self.title = @"推荐关注";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIEdgeInsets inset = UIEdgeInsetsMake(NYnavigationBarMaxY, 0, 0, 0);
    self.categoryTable.contentInset = inset;
    self.userTable.contentInset = inset;
    self.userTable.scrollIndicatorInsets = inset;
    
    self.categoryTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.categoryTable registerNib:[UINib nibWithNibName:@"NYFollowCategoryCell" bundle:nil] forCellReuseIdentifier:categorycell];
    
    [self.userTable registerNib:[UINib nibWithNibName:@"NYFollowTagCell" bundle:nil] forCellReuseIdentifier:usercell];

    self.userTable.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.userTable.rowHeight = 70;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.categoryTable) {
        return self.categoryarray.count;

    } else {

        if (self.categoryarray.count) {
            return NYSelectedCategory.users.count;

        }else
        {return 0;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.categoryTable) {
        NYFollowCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:categorycell];
        cell.category = self.categoryarray[indexPath.row];
        return cell;
    } else {
        NYFollowTagCell *cell = [tableView dequeueReusableCellWithIdentifier:usercell];
        NYFollowUser *user = NYSelectedCategory.users[indexPath.row];
        cell.user = user;
        
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView== self.userTable) {
        return;
    }
    if (NYSelectedCategory.users.count) {
        [self.userTable  reloadData];
        
    } else {
        [self.userTable reloadData];
        [self.userTable.header beginRefreshing];
        
    }
}
@end
